package com.qmmessage.sdk.common.util;

import com.qmmessage.sdk.common.exception.QmMessageSdkException;
import com.qmmessage.sdk.common.http.HttpResponse;
import com.qmmessage.sdk.constants.NamedThreadFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author qm
 */
public class QmHttpUtils {
    private static final int HTTP_SUCCESS_STATUS = 200;
    private static final int TIMEOUT_IN_MILLIONS = 50000;
    /**
     * http sync executor
     */
    private static final ExecutorService HTTP_SYNC_EXECUTOR = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 10,
            Runtime.getRuntime().availableProcessors() * 10,
            0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(10000),
            new NamedThreadFactory("httpSyncExecutor")
    );

    /**
     * sync callback interface
     */
    public interface Callback {
        /**
         * sync callback method
         * @param httpResponse http response entity
         */
        void onRequestComplete(HttpResponse httpResponse);
    }

    /**
     * async get method
     *
     * @param url      url
     * @param headers  header params
     * @param callback callback func
     */
    public static void doGetAsync(final String url, final Map<String, String> headers, final Callback callback) {
        HTTP_SYNC_EXECUTOR.submit(() -> {
            try {
                HttpResponse httpResponse = doGet(url, headers);
                if (callback != null) {
                    callback.onRequestComplete(httpResponse);
                }
            } catch (QmMessageSdkException e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * async post method
     *
     * @param url      url
     * @param content  request body
     * @param headers  header params
     * @param callback callback function
     */
    public static void doPostAsync(final String url, final String content, final Map<String, String> headers, final Callback callback) {
        HTTP_SYNC_EXECUTOR.submit(() -> {
            try {
                HttpResponse httpResponse = doPost(url, content, headers);
                if (callback != null) {
                    callback.onRequestComplete(httpResponse);
                }
            } catch (QmMessageSdkException e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * get method
     *
     * @param url     url
     * @param headers header params
     * @return response data
     * @throws QmMessageSdkException qm exception
     */
    public static HttpResponse doGet(String url, final Map<String, String> headers) throws QmMessageSdkException {
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (conn.getResponseCode() == HTTP_SUCCESS_STATUS) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return HttpResponse.successResponse(baos.toString());
            } else {
                StringBuilder result = new StringBuilder();
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()))) {
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        result.append(line);
                    }
                }
                return HttpResponse.errResponse(conn.getResponseCode(), result.toString());
            }
        } catch (Exception e) {
            throw new QmMessageSdkException(e.getMessage());
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (baos != null) {
                    baos.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException ignored) {
            }
        }
    }

    /**
     * post method
     *
     * @param url     url
     * @param content request body
     * @param headers header params
     * @return response data
     * @throws QmMessageSdkException qm exception
     */
    public static HttpResponse doPost(String url, String content, final Map<String, String> headers) throws QmMessageSdkException {
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            // 设置参数类型
            String requestProperty = conn.getRequestProperty("Content-Type");
            if (requestProperty == null || requestProperty.trim().isEmpty()) {
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            }
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            if (content != null && !content.trim().isEmpty()) {
                out = new PrintWriter(conn.getOutputStream());
                out.print(content);
                out.flush();
            }
            int responseCode = conn.getResponseCode();
            if (responseCode == HTTP_SUCCESS_STATUS) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                StringBuilder result = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                return HttpResponse.successResponse(result.toString());
            } else {
                StringBuilder result = new StringBuilder();
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()))) {
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        result.append(line);
                    }
                }
                return HttpResponse.errResponse(conn.getResponseCode(), result.toString());
            }
        } catch (IOException e) {
            throw new QmMessageSdkException(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException ignored) {

            }
        }

    }

}
